package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.websocket.WebSocketServer;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired // 订单
    OrderMapper orderMapper;

    @Autowired // 订单详细
    OrderDetailMapper orderDetailMapper;


    @Autowired // 地址簿
    AddressBookMapper addressBookMapper;

    @Autowired // 购物车
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        // 根据地址簿id查询地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        // 判断地址簿是否为空
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL); // 用户地址为空异常
        }

        // 根据购物车的用户id查询购物车
        ShoppingCart shoppingCart = new ShoppingCart(); // 购物车实体类
        Long userId = BaseContext.getCurrentId(); // 获取当前用户id
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL); // 购物车为空异常
        }

        // 1.向订单表插入1条数据
        Orders orders = new Orders(); // 创建订单表实体类

        BeanUtils.copyProperties(ordersSubmitDTO,orders); // 拷贝数据
        orders.setOrderTime(LocalDateTime.now()); // 下单时间
        orders.setStatus(Orders.PENDING_PAYMENT); // 订单状态
        orders.setPayStatus(Orders.UN_PAID); // 支付状态
        orders.setNumber(String.valueOf(System.currentTimeMillis())); // 订单号
        orders.setPhone(addressBook.getPhone()); // 电话
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setUserId(userId); // 下单用户id

        orderMapper.insert(orders); // 持久层

        // 订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail(); // 订单详细表对象
            BeanUtils.copyProperties(cart,orderDetail); // 把当前用户购物车中的每条数据拷贝到订单详细表
            orderDetail.setOrderId(orders.getId()); // 设置订单id
            orderDetailList.add(orderDetail);
        }

        // 2.向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList); // 持久层

        // 3.清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId); // 持久层


        // 4.封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByOpenid(String.valueOf(userId));

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Autowired // 导入
    private WebSocketServer webSocketServer;


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 长连接
        Map map = new HashMap();

        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+outTradeNo);

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     * @param historyOrdersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getList(HistoryOrdersPageQueryDTO historyOrdersPageQueryDTO) {

        // 创建订单实体类对象
        Orders orders = new Orders();
        // 设置当前用户id
        orders.setUserId(BaseContext.getCurrentId());
        // 分页插件
        PageHelper.startPage(historyOrdersPageQueryDTO.getPage(),historyOrdersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(orders);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据订单id查询订单
     */
    @Override
    public Orders getDetail(Long id) {

        Orders orders = orderMapper.getDetail(id);
        return orders;
    }

    /**
     * 根据id取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = new Orders(); // 创建订单对象
        orders.setId(id); // 设置订单id
        orders.setStatus(Orders.CANCELLED);
        orderMapper.cancel(orders);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 创建响应数据VO对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(orderMapper.statistics(Orders.TO_BE_CONFIRMED)); //待接单数量
        orderStatisticsVO.setConfirmed(orderMapper.statistics(Orders.CONFIRMED));  // 待派送数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS));  // 派送中数量

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders(); // 订单实体类
        orders.setId(ordersConfirmDTO.getId()); // 设置id
        orders.setStatus(Orders.CONFIRMED); // 设置状态
        orderMapper.update(orders); // 持久层
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders(); // 订单实体类
        orders.setId(ordersRejectionDTO.getId()); // 订单id
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason()); // 拒单原因
        orderMapper.update(orders); // 持久层
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders(); // 订单实体类
        orders.setId(ordersCancelDTO.getId()); // 订单id
        orders.setRejectionReason(ordersCancelDTO.getCancelReason()); // 取消原因
        orderMapper.update(orders); // 持久层

    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders(); // 订单实体类
        orders.setId(id); // 设置id
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS); // 设置状态
        orderMapper.update(orders); // 持久层
    }

    /**
     * 完成订单
     * @param ordersConfirmDTO
     */
    @Override
    public void complete(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders(); // 订单实体类
        orders.setId(ordersConfirmDTO.getId()); // 订单id
        orders.setStatus(Orders.COMPLETED); // 取消原因
        orderMapper.update(orders); // 持久层
    }




}
